<!--
 * @Author: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @Date: 2023-01-11 15:29:18
 * @LastEditors: error: error: git config user.name & please set dead value or install git && error: git config user.email & please set dead value or install git & please set dead value or install git
 * @LastEditTime: 2023-02-13 14:39:45
 * @FilePath: \blog\Web\WebApplication\html\debounce.html
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>函数防抖示例代码实现</title>
    <style type="text/css">
        .container {
            width: 100vw;
            height: 100vh;
        }
    </style>
</head>

<body>
    <div class="container">
        <button onclick="btnFunc()">点击防抖</button>
    </div>
    <script type="text/javascript">
        let funcReturn
        //第一步 声明一个防抖函数
        function debounce(func, wait) {
            //声明一个内部函数定时器
            let timer = null;
            //产生闭包
            return function () {
                //如果不为空先清除
                if (timer != null) {
                    console.log("time存在")
                    clearTimeout(timer)
                } else {
                    console.log("time不存在")
                }
                timer = setTimeout(function () {
                    func.apply(this, arguments)
                }, wait)
            }
        }
        //函数防抖点击事件操作
        function btnFunc() {
            if (!funcReturn) {
                funcReturn = debounce(() => {
                    console.log("吃饭")
                }, 3000)
            }
            funcReturn()
        }

        function throttle(func, delay) {
            let lastTime = 0;
            return (...args) => {
                let now = Date.now();
                if (now - lastTime > delay) {
                    console.time();
                    func.call(this, args);
                    console.timeEnd();
                    lastTime = now;
                }
            }
        }
     
    </script>
</body>

</html>